package cn.edu.zhku.citrusmonitor.qa.controller;



import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.edu.zhku.citrusmonitor.domain.QA;

import cn.edu.zhku.citrusmonitor.domain.TbQuestion;
import cn.edu.zhku.citrusmonitor.domain.TbUser;
import cn.edu.zhku.citrusmonitor.qa.service.QuestionService;
import cn.edu.zhku.citrusmonitor.qa.service.QuestionServiceImpl;
import cn.edu.zhku.citrusmonitor.util.BaseServlet;
import cn.edu.zhku.citrusmonitor.util.Message;
import cn.edu.zhku.citrusmonitor.util.PageBean;
import cn.edu.zhku.citrusmonitor.util.UUIDUtils;
import cn.edu.zhku.citrusmonitor.util.WebUtils;

import net.sf.json.JSONObject;

@WebServlet("/question.do")
public class QuestionServlet extends BaseServlet {
	
	private static final long serialVersionUID = 1L;
	
	QuestionService qs=new QuestionServiceImpl();
	
	
	public JSONObject addQ(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (!ServletFileUpload.isMultipartContent(request)) {  
	        return JSONObject.fromObject(new Message("2", "不是请求的信息表单，请确认表单属性是否正确")); 
	    }  
	      
	  
	        //调用工具类，获得上传文件信息  
	    	
	    	//表单要有summary，content，filePath(filename)
	    	TbQuestion question=WebUtils.doFileUpload(request);  
	    	
	    	TbUser user=(TbUser) request.getSession().getAttribute("user");
	    	if(user!=null) {
	    		String username=user.getRealName();
		    	String userid=user.getUserId();
		    	question.setPresenter(username);    					    			
		        question.setUserId(userid);       
	    	}
	    	 question.setQuestionId(UUIDUtils.getId());//生成唯一id
	        qs.addQ(question);//保存上传文件信息  
	          
	        return JSONObject.fromObject(new Message("1", "上传成功"));
	      
	  
	}


	
	public JSONObject modifyQ(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (!ServletFileUpload.isMultipartContent(request)) {  
	        return JSONObject.fromObject(new Message("2", "不是请求的信息表单，请确认表单属性是否正确")); 
	    }  
	      
	   
	        //调用工具类，获得上传文件信息  
  	
	    	//表单要有summary，content，filePath
	    	TbQuestion question=WebUtils.doFileUpload(request);  
 
	        qs.modifyQ(question);//保存上传文件信息  
	          
	        return JSONObject.fromObject(new Message("1", "修改成功"));
	      
	   
	}
	
	//批量删除
			public JSONObject delAll(HttpServletRequest request, HttpServletResponse response) throws SQLException{
				String[] ids = request.getParameterValues("ids");
				
				
					if(qs.delAll(ids)==1)
					{
						return JSONObject.fromObject(new Message("1", "删除公告成功"));
					}
					return JSONObject.fromObject(new Message("2", "删除公告失败"));
				
			}
	
	
	public JSONObject removeQ(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String questionId=request.getParameter("questionId");
		
		
			if(qs.removeQ(questionId)==1) {
				
				return JSONObject.fromObject(new Message("1", "删除问题成功"));
			}
			return JSONObject.fromObject(new Message("2", "删除问题失败"));	
	

	
	}
	
	//Ajax搜索框显示数据，显示所有问题
	public String findQByWord(HttpServletRequest request, HttpServletResponse response) throws Exception {
	
			String word=request.getParameter("word");
			System.out.println(word);
			List<TbQuestion> list = new ArrayList<TbQuestion>();
			
			list=qs.findQAByWord(word);
			for(TbQuestion que:list){
				System.out.println(que.getContent());
			}
			if(list!=null) {
				return JSONArray.toJSONString(list);	
			}
		
			return JSON.toJSONString(new Message("2", "无此结果"));
	}
	
	//查询问题总数
	public int showQCount(HttpServletRequest request, HttpServletResponse response) throws SQLException{
		String status=request.getParameter("status");
		if(status.equals("0")) {
			status="未回复";
		}
		else if(status.equals("1")) {
			status="已回复";
		}
		
		return qs.showQCount(status);
		
	}
	
	
	
	//显示问题
	public String showQ(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String status=request.getParameter("status");
		if(status.equals("0")) {
			status="未回复";
		}
		else if(status.equals("1")) {
			status="已回复";
		}
		//初始化每页显示的记录数
		int pageSize =0;
		String pageSize1 = request.getParameter("pageSize");
		if(pageSize1!=null) {
			pageSize = Integer.parseInt(pageSize1);
		}
		else {
			pageSize=4;
		}
	
		int currentPage = 1;//当前页
		String currPage = request.getParameter("currentPage");//从上一页或下一页得到的数据
		if(currPage!=null&&!"".equals(currPage)){//第一次访问资源时，currPage可能是null
			currentPage = Integer.parseInt(currPage);
		}
		//分页查询，并返回PageBean对象
		List<TbQuestion> questionlist = qs.showQ(currentPage,pageSize,status);
		
	return JSON.toJSONStringWithDateFormat(questionlist, "yyyy-MM-dd", SerializerFeature.EMPTY);	
	}
	
	//首页显示前几条问题
	public String showQAll(HttpServletRequest request, HttpServletResponse response) {
			int pageSize=0;
			String pageSize1=request.getParameter("pageSize");
			if(pageSize1!=null) {
				pageSize = Integer.parseInt(pageSize1);
			}
			else {
				pageSize=4;
			}
							
			List<TbQuestion> quest = qs.showQAll(pageSize);
			
			return JSONArray.toJSONString(quest);	
	}
	
	
	//显示已经回答的问题和答案
	public JSONObject showQAByQid(HttpServletRequest request, HttpServletResponse response) throws SQLException {
		
		
			String questionId=request.getParameter("questionId");		
			QA qa=qs.showQAByQid(questionId);
			return JSONObject.fromObject(qa);		
	}
	
	
	
	//判断用户是否已经登录
		public int loadStatus(HttpServletRequest request, HttpServletResponse response) throws SQLException{
			TbUser user= (TbUser) request.getSession().getAttribute("user");
			
		
			if(user==null) {
				return 0;
			}
			else {
				String userId=user.getUserId();
				String userPassword =qs.findUserPasswordById(userId);
				if( userPassword.equals(user.getPassword())) {
					return 1;
				}
				else
					return 0;
			}
			
		}
		
		//后台管理，显示全部
		public String showAll(HttpServletRequest request, HttpServletResponse response) throws SQLException {
			
			int currentPage=0;
			String currentPage1=request.getParameter("currentPage");
			if(currentPage1!=null) {
				currentPage = Integer.parseInt(currentPage1);
			}
			else {
				currentPage=4;
			}
			
			int pageSize=0;
			String pageSize1=request.getParameter("pageSize");
			if(pageSize1!=null) {
				pageSize = Integer.parseInt(pageSize1);
			}
			else {
				pageSize=4;
			}
			
			PageBean<TbQuestion> pb=new PageBean<TbQuestion>();
			pb=qs.showAll(currentPage,pageSize);
			
			return JSON.toJSONString(pb);
			
		}
}
